package com.xilihui.xlh.business.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.xilihui.xlh.R;
import com.xilihui.xlh.business.entities.LoginEntity;
import com.xilihui.xlh.business.requests.LoginRequest;
import com.xilihui.xlh.constant.StrConst;
import com.xilihui.xlh.core.app.BaseCompatActivity;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.CountDown;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.TextExtend;
import com.xilihui.xlh.core.util.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/6/5.
 */

public class ForgetActivity extends BaseCompatActivity implements View.OnClickListener {
    
    
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.tv_sendCode)
    TextView tv_sendCode;
    @BindView(R.id.tv_login)
    TextView tv_login;
    
    int type = 1;//1（发送验证码）2（确定）
    private CountDown countDown;
    private long time = 0L;
    private String phone = "";
    private String code = "";
    private String access_token = "";
    private String user_id = "";
    
    
    @Override
    public int getLayout() {
        return R.layout.activity_forget;
    }
    
    @OnClick(R.id.iv_close)
    public void back(){
        if(type==1){
            type = 2;
            finish();
        }else {
            type = 1;
            et_phone.setText("");
            et_code.setText("");
            et_phone.setInputType(InputType.TYPE_CLASS_PHONE);
            et_code.setInputType(InputType.TYPE_CLASS_PHONE);
            et_phone.setHint("手机号码");
            et_code.setHint("验证码");
            tv_sendCode.setVisibility(View.VISIBLE);
            tv_login.setText("下一步");
        }
    }

    @Override
    public String initTitle() {
        return null;
    }

    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {
        tv_sendCode.setOnClickListener(this);
        initcountDown();
    }

    @Override
    public void initData() {
        
    }
    
    @OnClick(R.id.tv_login)
    public void login(){
        if(type==1){
            
            verify();
           
        }else {
            setPasswd();
        }
       
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_sendCode:
                LogUtil.i("mylog","发送验证码");
                sendCode();
                break;
        }
    }

    public void initcountDown(){

        countDown = new CountDown();
        countDown.setTextOnCounting("", "重新发送");
        countDown.setTextOnFinished("发送验证码");
        countDown.setTv(tv_sendCode);

        time = (long) SPUtil.get(this,"time",0L);
        long curTime = System.currentTimeMillis();
        long residueTime = time-curTime;
        LogUtil.i("mylog","time:"+time+"\ncurTime:"+curTime+"\nresidueTime"+residueTime);
        long duration = residueTime/1000;
        LogUtil.i("mylog","duration:"+duration);
        if(duration>0){
            LogUtil.i("mylog","执行");
            countDown.execute((TextView) tv_sendCode, duration, new CountDown.Callback() {
                @Override
                public void onStart() {
                    tv_sendCode.setSelected(false);
                }

                @Override
                public void onCounting(TextView tv, long second, String text) {
                    SPUtil.put(ForgetActivity.this,"time",System.currentTimeMillis()+second*1000);
                    LogUtil.i("mylog","set time:"+System.currentTimeMillis());
                }

                @Override
                public void onFinish() {
                    tv_sendCode.setSelected(true);
                }
            });
        }
    }

    /**
     * 发送验证码
     */
    public void sendCode(){
        
        String phone = et_phone.getText().toString().trim();
        
        if(TextUtils.isEmpty(phone)){
            ToastUtil.toastShortNegative("请输入手机号码");
            return;
        }
        
        if(!TextExtend.isMobile(phone)){
            ToastUtil.toastShortNegative("请输入正确的手机号码");
            return;
        }
        
        tv_sendCode.setEnabled(false);
        
        LoginRequest.sendCode(phone, StrConst.scene_gxmm)
                .compose(DoTransform.<BaseEntity>applyLoading(this))
                .compose(ForgetActivity.this.<BaseEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<BaseEntity>(ForgetActivity.this) {
                    @Override
                    protected void onSuccess(BaseEntity entity) {
                        tv_sendCode.setEnabled(true);     
                        ToastUtil.toastShortPositive(entity.getMsg());
                        countDown.execute(tv_sendCode, 60, new CountDown.Callback() {
                            @Override
                            public void onStart() {
                                tv_sendCode.setSelected(false);
                            }

                            @Override
                            public void onCounting(TextView tv, long second, String text) {
                                SPUtil.put(ForgetActivity.this,"time",System.currentTimeMillis()+second*1000);
                                LogUtil.i("mylog","set time:"+System.currentTimeMillis());
                            }

                            @Override
                            public void onFinish() {
                                tv_sendCode.setSelected(true);
                            }
                        });
                    }

                    @Override
                    protected void onFail(String msg) {
                        tv_sendCode.setEnabled(true);
                        ToastUtil.toastShortPositive(msg);
                    }
                });
    }

    /**
     * 验证
     */
    public void verify(){
        
        phone = et_phone.getText().toString().trim();
        code = et_code.getText().toString().trim();
        
        if(TextUtils.isEmpty(phone)){
            ToastUtil.toastShortNegative("请输入手机号码");
            return;
        }
        
        if(!TextExtend.isMobile(phone)){
            ToastUtil.toastShortNegative("请输入正确的手机号码");
            return;
        }
        
        
        LoginRequest.forget(phone,code)
                .compose(DoTransform.<LoginEntity>applyLoading(this))
                .compose(ForgetActivity.this.<LoginEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<LoginEntity>(ForgetActivity.this) {
                    @Override
                    protected void onSuccess(LoginEntity entity) {
                        ToastUtil.toastShortPositive(entity.getMsg());
                        access_token = entity.getAccess_token();
                        SPUtil.put(ForgetActivity.this,SPUtil.TOKEN,access_token);
                        user_id = entity.getUser_id();
                        
                        et_code.setText("");
                        et_phone.setText("");
                        et_phone.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|InputType.TYPE_CLASS_TEXT);
                        et_code.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|InputType.TYPE_CLASS_TEXT);
                        et_code.setHint("确认新密码");
                        et_phone.setHint("设置新密码");
                        et_code.clearFocus();
                        et_phone.requestFocus();
                        tv_sendCode.setVisibility(View.GONE);
                        tv_login.setText("确认");

                        type = 2;
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                    }
                });
        
    }

    /**
     * 设置密码
     */
    public void setPasswd(){
        
        String passwd = et_phone.getText().toString().trim();
        String surePasswd = et_code.getText().toString().trim();
        
        if(TextUtils.isEmpty(passwd)){
            ToastUtil.toastShortNegative("请输入新密码");
            return;
        }
        
        if(passwd.length()<6||passwd.length()>16){
            ToastUtil.toastShortNegative("请输入6~16位密码");
            return;
        }
        
        if(TextUtils.isEmpty(surePasswd)){
            ToastUtil.toastShortNegative("请输入确认新密码");
            return;
        }
        
        if(surePasswd.length()<6||surePasswd.length()>16){
            ToastUtil.toastShortNegative("请输入6~16位新密码");
            return;
        }
        
        if(!passwd.equals(surePasswd)){
            ToastUtil.toastShortNegative("两次密码不一致");
            return;
        }
        
        LoginRequest.forgetNext(access_token,passwd,surePasswd,user_id)
                .compose(DoTransform.<BaseEntity>applyLoading(this))
                .compose(ForgetActivity.this.<BaseEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<BaseEntity>(this) {
                    @Override
                    protected void onSuccess(BaseEntity entity) {
                        ToastUtil.toastShortPositive(entity.getMsg());     
                        finish();
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                    }
                });
        
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(countDown!=null){
            countDown.cancel();
        }
    }
    
}
